<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24" style="width: 100%;">
        <el-card shadow="hover">
          <!-- 选择会议下拉框 -->
          <div style="margin-bottom: 20px;">
            <el-select
              v-model="selectedConferenceId"
              placeholder="请选择会议"
              filterable
              clearable
              style="width: 300px;"
              @change="onConferenceChange"
            >
              <el-option
                v-for="conf in conferences"
                :key="conf.conferenceId"
                :label="conf.conferenceName"
                :value="conf.conferenceId"
              />
            </el-select>
          </div>

          <!-- 图表区域 -->
          <el-col :span="24">
            <el-card shadow="hover">
              <div v-if="!selectedConferenceId || options.labels.length === 0" class="empty-text">
                请选择对应的会议
              </div>
              <schart
                v-else
                ref="bar"
                class="schart"
                canvasId="bar"
                :options="options"
              />
            </el-card>
          </el-col>

        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Schart from 'vue-schart';
import requets from '../utils/request';

export default {
  name: 'DashboardMap',
  components: {
    Schart
  },
  data() {
    return {
      name: this.$store.state.user.username,
      statisticsData: [],
      conferences: [],
      selectedConferenceId: null,
      options: {
        type: 'bar',
        title: {
          text: '各省份各类型报名统计'
        },
        xRorate: 25,
        labels: [],
        datasets: []
      }
    };
  },
  computed: {
    role() {
      return this.name === 'admin' ? '超级管理员' : '普通用户';
    }
  },
  methods: {
    async loadStatistics() {
      try {
        const res = await requets.get('/conferences/selectAll');
        this.conferences = res;
        this.selectedConferenceId = res[0].conferenceId
        this.onConferenceChange(res[0].conferenceId)
      } catch (e) {
        this.$message.error('加载会议列表失败');
      }
    },

    async onConferenceChange(conferenceId) {
      if (!conferenceId) {
        this.options.labels = [];
        this.options.datasets = [];
        return;
      }

      try {
        const res = await requets.get('/participants/statistics', {
          conferencesId: conferenceId
        });

        if (Array.isArray(res)) {
          this.statisticsData = res;
          this.processChartData(); // 处理图表数据
        } else {
          this.$message.error('获取报名数据失败');
        }
      } catch (error) {
        console.error('接口错误', error);
        this.$message.error('服务器异常');
      }
    },

    processChartData() {
      const provinceSet = new Set();
      const typeMap = new Map(); // typeName => Map<province, count>

      this.statisticsData.forEach(item => {
        const province = item.province || '未知';
        const type =
          item.participantTypes && item.participantTypes.typeName
            ? item.participantTypes.typeName
            : '未知';
        const count = item.paidCount || 0;

        provinceSet.add(province);

        if (!typeMap.has(type)) {
          typeMap.set(type, new Map());
        }

        const provinceCountMap = typeMap.get(type);
        provinceCountMap.set(province, (provinceCountMap.get(province) || 0) + count);
      });

      const provinces = Array.from(provinceSet);
      const datasets = [];

      typeMap.forEach((provinceMap, typeName) => {
        const data = provinces.map(p => provinceMap.get(p) || 0);
        datasets.push({
          label: typeName,
          data: data
        });
      });

      this.options = {
        type: 'bar',
        title: {
          text: '各省份各类型报名统计'
        },
        xRorate: 25,
        labels: provinces,
        datasets: datasets
      };
    },

    handleResize() {
      const chart = this.$refs.bar;
      if (chart && chart.resize) {
        chart.resize();
      }
    }
  },

  mounted() {
    this.loadStatistics();
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.schart {
  width: 100%;
  height: 300px;
}
.empty-text {
  text-align: center;
  font-size: 18px;
  color: #999;
  padding: 100px 0;
}
</style>